package leetcode.code0931;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

//执行用时：5 ms, 在所有 Java 提交中击败了61.52%的用户
//
//内存消耗：38.7 MB, 在所有 Java 提交中击败了90.14%的用户
//
//通过测试用例：49 / 49
public class Solution implements IDebug {

	public int minFallingPathSum(int[][] matrix) {
		int m = matrix.length, n = matrix[0].length;
		int[][] dp = new int[m][n];
		for (int i = 0; i < n; i++) {
			dp[0][i] = matrix[0][i];
		}
		for (int i = 1; i < m; i++) {
			for (int j = 0; j < n; j++) {
				int min = dp[i - 1][j];
				if (j - 1 >= 0) {
					min = Math.min(dp[i - 1][j - 1], min);
				}
				if (j + 1 < n) {
					min = Math.min(dp[i - 1][j + 1], min);
				}
				dp[i][j] = matrix[i][j] + min;
			}
		}
		int ans = Integer.MAX_VALUE;
		for (int i = 0; i < n; i++) {
			ans = Math.min(ans, dp[m - 1][i]);
		}
		return ans;
	}

	@Override
	public void debug1() {
		HelpDebug.compare(13, this.minFallingPathSum(HelpDebug.str2array1("[[2,1,3],[6,5,4],[7,8,9]]")));

	}

	@Override
	public void debug2() {
		HelpDebug.compare(-59, this.minFallingPathSum(HelpDebug.str2array1("[[-19,57],[-40,-5]]")));
	}

	@Override
	public void debug3() {
		HelpDebug.compare(-48, this.minFallingPathSum(HelpDebug.str2array1("[[-48]]")));
	}

	@Override
	public void debug4() {
		HelpDebug.compare(13, this.minFallingPathSum(HelpDebug.str2array1("[[2,1,3],[6,5,4],[7,8,9]]")));
	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
	}

}
